package com.zhouyibike.uu.ui.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.BookingResult;
import com.zhouyibike.uu.entity.FindBictcleByRangeResult;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.entity.KaiSuoResult;
import com.zhouyibike.uu.entity.LocationInfo;
import com.zhouyibike.uu.entity.LoginResult;
import com.zhouyibike.uu.entity.MyReceiverResult;
import com.zhouyibike.uu.entity.MyRidingResult;
import com.zhouyibike.uu.entity.OrderUnPayNewResult;
import com.zhouyibike.uu.entity.SettingResult;
import com.zhouyibike.uu.entity.StartRidingInfo;
import com.zhouyibike.uu.entity.StartRidingResult;
import com.zhouyibike.uu.entity.TwentyActivityResult;
import com.zhouyibike.uu.entity.YuYueInfo;
import com.zhouyibike.uu.entity.YuYueResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.listener.MyOrientationListener;
import com.zhouyibike.uu.service.LockService;
import com.zhouyibike.uu.ui.activity.hehuoren.ChengshihehuorenActivity;
import com.zhouyibike.uu.ui.activity.hehuoren.ChengshihehuorenbuybikeActivity;
import com.zhouyibike.uu.ui.activity.hehuoren.ChengshihehuorenxiangqingActivity;
import com.zhouyibike.uu.ui.activity.hehuoren.DanchehehuorenxiangqingActivity;
import com.zhouyibike.uu.ui.activity.jvbaoandpaiming.JvBaoActivity;
import com.zhouyibike.uu.ui.activity.mybike.MybikeActivity6;
import com.zhouyibike.uu.ui.activity.mybike.Twentyoffer.Buy20SuccessActivity;
import com.zhouyibike.uu.ui.activity.mybike.Twentyoffer.PayActivity20;
import com.zhouyibike.uu.ui.activity.mywallet.ChongZhiActivity;
import com.zhouyibike.uu.ui.activity.mywallet.MyWalletActivity4;
import com.zhouyibike.uu.ui.activity.share.MyShareMsgActivity3;
import com.zhouyibike.uu.ui.activity.web.ZhiNanActivity;
//import com.zhouyibike.zy.ui.activity.xingcheng.CaptureActivity;
import com.zhouyibike.uu.ui.activity.xingcheng.MyJourneyActivity;
import com.zhouyibike.uu.ui.activity.yihoudong.YihuodongActivity3;
import com.zhouyibike.uu.ui.activity.yihoudong.YihuodongActivity4;
import com.zhouyibike.uu.ui.activity.youhuihuodong.HuodongduihuanActivity;
import com.zhouyibike.uu.ui.activity.zxingabout.DeviceScanActivity;
import com.zhouyibike.uu.ui.activity.zxingabout.OpenResultActivity;
import com.zhouyibike.uu.ui.adapter.LeftItemAdapter;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.base.MyApplication;
import com.zhouyibike.uu.ui.view.Countdown;
import com.zhouyibike.uu.ui.view.TXCircleImageView;
import com.zhouyibike.uu.utils.DataSingle;
import com.zhouyibike.uu.utils.ImgUtils;
import com.zhouyibike.uu.utils.PermissionTool;
import com.zhouyibike.uu.utils.TextUtils;
import com.zhouyibike.uu.utils.TimeUtils;
import com.zhouyibike.uu.utils.Util;
import com.zhouyibike.uu.utils.WalkingRouteOverlay;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

import static cn.jpush.android.api.JPushInterface.setAlias;

public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener, OnGetRoutePlanResultListener {
    private ImageButton mBtnBack;
    private TextView mBtnTitle;
    //
//    private final int SDK_PERMISSION_REQUEST = 127;
    private ListView leftlv;
    private LeftItemAdapter leftItemAdapter;
    private DrawerLayout drawer;
    private TextView tvname, tvstate;
    private TXCircleImageView left_userIcon;
    private LinearLayout ll_state;
    private ImageView iv_state;
    private ImageView iv_morelogin;
    private ImageView iv_mylocation, iv_refresh, iv_scan;
    private Myhandler myhandler;
    private LinearLayout ll_fjwdc, zongshezhily;
    private int maxmin, maxsec;//预约时长
    private Long timehapast;
    private String money_unit;
    // 定位相关
    LocationClient mLocClient;
    private LinearLayout ll_yydc;//预约单车界面
    private LinearLayout ll_yydc_succ, huodongmaduihuan;//活动兑换ly
    private LinearLayout ll_chong20;//充20送单车界面
    public MyLocationListenner myListener = new MyLocationListenner();
    private ArrayList<BluetoothDevice> mLeDevices;
    private BluetoothDevice currentDevice;
    private boolean isshuaxin = false;
    private boolean isshuaxining = false;
    /**
     * 方向传感器的监听器
     */
    private MyOrientationListener myOrientationListener;
    private UUID[] uuids = new UUID[]{
            LockService.RX_SERVICE_UUID
    };
    /**
     * 当前的精度
     */
    private float mCurrentAccracy;
    /**
     * 方向传感器X方向的值
     */
    private int mXDirection;
    private TextureMapView mMapView = null;
    private BaiduMap mBaiduMap;
    private boolean islogin = false;
    private double centerlat, centerlng;
    private double mylat, mylng;
    private double endlat, endlng;//点击车辆位置信息
    private String endnum;//点击车辆编号 预约车辆编号
    private RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用
    //    private boolean isbooking=false;//是否有预约单车
    private String distence, usetime, userlocation;
    private WalkingRouteOverlay overlay;
    private WalkingRouteResult walkingRouteResult;
    private GeoCoder mSearchgc = null;
    private ImageView iv_center, titleiv;
    private ImageView iv_tel;
    private boolean isyysuccess = false;//是否有预约单车
    private boolean islocation = false;//判断时候定位
    private boolean isriding = false;//判断是否正在骑车
    private PopupWindow window;
    private RelativeLayout bar_btn_rly;
    private Button popbutton;
    private TextView drivetime, drivefar, drivehot, bikenum, pricepop;
    private boolean shouldshowending = false;
    private RelativeLayout barly;
    private Animation operatingAnim, shakeAnim2;
    private ArrayList<Marker> markers = new ArrayList<>();
    private Dialog teldialog;
    private boolean firstanim = true;//是否第一次动画
    private double zoomnum = 0;
    private double shuaxinlat, shuaxinlng;//刷新位置
    private boolean hastongzhi = true;
    private ImageView iv20huodongtitile;
    private List<TwentyActivityResult.DataBean.ImagesBean> imagesBeen = new ArrayList<>();
    private boolean hasbuy20danche = false;
    private int huodongdanche20 = 0;
    private Dialog jubaodialog;//举报对话框
    private TextView tvdongjie;
    private ImageView ivdongjie;
    public boolean has20 = false;
    private Dialog firstkaisuodialog;
    private boolean iszhunhehuoren = true;//准合伙人
    private boolean ischenghsihehuoren = false;//合伙人

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        // getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setrotatanim();
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);
        mSearchgc = GeoCoder.newInstance();
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        mLeDevices = new ArrayList<>();
        leftItemAdapter = new LeftItemAdapter(this);
        if (TextUtils.isNullorEmpty(preferences.getString("mobile", ""))) {
            islogin = false;
        } else {
            islogin = true;
        }
        qixingjuli = preferences.getFloat("qixingjuli", 0f);
        initView();
        setUpDrawer();
        myhandler = new Myhandler();
        locationmsg();
        initOritationListener();
        has20danche();
        if (islogin) {
            try {
                setAlias(this, preferences.getString("mobile", ""), null);
            } catch (Exception e) {
                e.printStackTrace();
                setAlias(this, "", null);
            }
//            initLeft();
//            if (preferences.getString("status", "").equals("3")) {
//                getSettings();
//            }else  if (preferences.getString("status", "").equals("11")) {
//                //冻结
//
//            }
            reloadAccountInfo();
        }
        setDrivingpop();
        setteldialog();
        setjubaoDialog();
//        TwentyActivityResult zz=null;
//        Log.e( "onCreate: ",zz.getMessage() );
    }

    private void setrotatanim() {//设置动画
        operatingAnim = AnimationUtils.loadAnimation(this, R.anim.myrotating);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        shakeAnim2 = AnimationUtils.loadAnimation(this, R.anim.shake_y);
        // shakeAnim2.setInterpolator(lin);

    }

    private void initView() {
        zongshezhily = (LinearLayout) findViewById(R.id.zongshezhi);

        zongshezhily.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                String appId = "你的ID";//开发者平台ID
//                IWXAPI api = WXAPIFactory.createWXAPI(MainActivity.this, "wx6a982211ac5a6a48", false);
//
//                if (api.isWXAppInstalled()) {
//                    JumpToBizProfile.Req req = new JumpToBizProfile.Req();
//                    req.toUserName = "gh_d2faf42gadbc"; // 公众号原始ID
//                    req.extMsg = "";
//                    req.profileType = JumpToBizProfile.JUMP_TO_NORMAL_BIZ_PROFILE; // 普通公众号
//                    api.sendReq(req);
//                }else{
//                    Toast.makeText(MainActivity.this, "微信未安装", Toast.LENGTH_SHORT).show();
//                }
                if (!islogin) {
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
                    drawer.closeDrawer(GravityCompat.START);
                } else {
                    startActivityForResult(new Intent(MainActivity.this, MineActivity.class), 100);
                    drawer.closeDrawer(GravityCompat.START);
                }
            }
        });
        tvdongjie = (TextView) findViewById(R.id.tvdongjie);
        ivdongjie = (ImageView) findViewById(R.id.iv_mian_scan2);
//        android:src="@drawable/chong20hengtiao"
        iv20huodongtitile = (ImageView) findViewById(R.id.ll_main_chong20songdancheiv);
        ll_chong20 = (LinearLayout) findViewById(R.id.ll_main_chong20songdanche);
        ll_chong20.setOnClickListener(this);
        barly = (RelativeLayout) findViewById(R.id.barly);
        barly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (shouldshowending) {
                    if (window.isShowing()) {
                        window.dismiss();
                    }
                }
                drawer.openDrawer(GravityCompat.START);
            }
        });
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnBack.setBackgroundResource(R.drawable.my);
        //  mBtnTitle.setText(R.string.app_name);
//        RelativeLayout.LayoutParams linearParams =(RelativeLayout.LayoutParams) mBtnTitle.getLayoutParams(); //取控件textView当前的布局参数
//        linearParams.height = Util.dp2px(this,24);// 控件的高强制设成20
//        linearParams.width = Util.dp2px(this,110);// 控件的宽强制设成30
//        mBtnTitle.setLayoutParams(linearParams); //使设置好的布局参数应用到控件</pre>
//        mBtnTitle.setBackground(getResources().getDrawable(R.mipmap.yishuzi));
//        mBtnTitle.setVisibility(View.GONE);
        titleiv = (ImageView) findViewById(R.id.titleiv);
        titleiv.setImageDrawable(getResources().getDrawable(R.drawable.yishuzi));
        titleiv.setVisibility(View.VISIBLE);
//        Util.setRtitle(titleiv, 314.0, 80.0, Util.dp2px(this, 22));
        mBtnBack.setOnClickListener(this);
        bar_btn_rly = (RelativeLayout) findViewById(R.id.bar_btn_rly);
        iv_center = (ImageView) findViewById(R.id.iv_map_center);//中心指针
        ll_fjwdc = (LinearLayout) findViewById(R.id.ll_main_fjwdc);
        leftlv = (ListView) findViewById(R.id.id_lv_left_menu);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                if (slideOffset < 1) {
                    if (window.isShowing()) {
                        window.dismiss();
                    }
                }
            }

            @Override
            public void onDrawerOpened(View drawerView) {

            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {
                Log.e("onDrawerOpened: ", "1");
                if (drawer.isDrawerOpen(GravityCompat.START)) {
                    if (window.isShowing()) {
                        window.dismiss();
                    }
                } else {
                    if (shouldshowending) {
                        showdrivingpop();
                    }
                }
                if (!islogin) {
                    iv_scan.setVisibility(View.VISIBLE);
                    iv_scan.setEnabled(true);
                    iv_tel.setVisibility(View.VISIBLE);
                    iv_tel.setEnabled(true);
                }
            }
        });
        ll_yydc = (LinearLayout) findViewById(R.id.ll_main_yydc_new);
        ll_yydc_succ = (LinearLayout) findViewById(R.id.ll_main_yydcsucc_new);
        iv_tel = (ImageView) findViewById(R.id.imageView4);
        iv_tel.setOnClickListener(this);

        mMapView = (TextureMapView) findViewById(R.id.bmapView);
        mMapView.showZoomControls(false);//缩放去掉
        mMapView.showScaleControl(false);//去除比例尺控件
        View child = mMapView.getChildAt(1);//logo去掉
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }
//        mMapView.setOnClickListener(this);
        iv_mylocation = (ImageView) findViewById(R.id.iv_map_mylocation);
        iv_mylocation.setOnClickListener(this);
        iv_refresh = (ImageView) findViewById(R.id.iv_map_refresh);
        iv_refresh.setOnClickListener(this);
        iv_refresh.setVisibility(View.INVISIBLE);
        iv_scan = (ImageView) findViewById(R.id.iv_mian_scan);
        iv_scan.setOnClickListener(this);
        huodongmaduihuan = (LinearLayout) findViewById(R.id.huodongmaduihuan);
        huodongmaduihuan.setOnClickListener(this);
    }

    private Dialog yzmdialog;

    /**
     * 信息显示dialog
     */
    private void initDailog(int type) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.total_show_dialog, null);
        yzmdialog = new Dialog(this, R.style.loading_dialog);
        Button btn_sure = (Button) view.findViewById(R.id.btn_total_show_sure);
        TextView tv_msg = (TextView) view.findViewById(R.id.tv_total_show_msg);

        if (type == 1) {
            tv_msg.setText("您尚未完成实名认证");
            btn_sure.setText("去认证");
            btn_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                    yzmdialog.dismiss();
                }
            });
        } else if (type == 2) {
            tv_msg.setText("您尚未完成骑行充值");
            btn_sure.setText("去缴费");
            btn_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                    yzmdialog.dismiss();
                }
            });
        } else if (type == 3) {
            tv_msg.setText("您当前的余额已低于" + minmoneyforriding + "元,为不影响您的正常使用,请充值");
            btn_sure.setText("请充值");
            btn_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, ChongZhiActivity.class);
                    intent.putExtra("isformmaincz", true);
                    startActivityForResult(intent, 10000);
                    yzmdialog.dismiss();
                }
            });
        }
        ImageView iv_dismis = (ImageView) view.findViewById(R.id.iv_codedialog_dismis);
        iv_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yzmdialog.dismiss();
            }
        });
        yzmdialog.setContentView(view, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        yzmdialog.setCancelable(true);
        yzmdialog.setCanceledOnTouchOutside(false);
        yzmdialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

    private void initLeft() {
        ll_state.setVisibility(View.VISIBLE);
        iv_morelogin.setVisibility(View.GONE);
        ishaveenoughmoney(false);
        try {
            //图片过大需压缩
            Picasso.with(this).load(preferences.getString("headPicture", "")).transform(ImgUtils.Picassocompress(left_userIcon)).networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE).error(R.mipmap.head_moren).placeholder(R.mipmap.head_moren).into(left_userIcon);
        } catch (Exception e) {

        }
        if (!TextUtils.isNullorEmpty(preferences.getString("nickName", ""))) {
            tvname.setText(preferences.getString("nickName", ""));
        } else if (!TextUtils.isNullorEmpty(preferences.getString("fullName", ""))) {
            tvname.setText(preferences.getString("fullName", ""));
        } else {
            tvname.setText(TextUtils.toFormatPhone(preferences.getString("mobile", "")));
        }
    }

    private void setUpDrawer() {
        LinearLayout addheadview = (LinearLayout) findViewById(R.id.addheadview);
        LayoutInflater inflater = LayoutInflater.from(this);
        View head = inflater.inflate(R.layout.nav_header_main_new, leftlv, false);
        tvname = (TextView) head.findViewById(R.id.tv_head_name);
        iv_morelogin = (ImageView) head.findViewById(R.id.tv_head_morelogin);
        left_userIcon = (TXCircleImageView) head.findViewById(R.id.left_userIcon);
        tvstate = (TextView) head.findViewById(R.id.tv_head_state);
        ll_state = (LinearLayout) head.findViewById(R.id.ll_lefthead_state);
        iv_state = (ImageView) head.findViewById(R.id.iv_lefthead_state);
        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!islogin) {
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
                    drawer.closeDrawer(GravityCompat.START);
                } else {
                    startActivityForResult(new Intent(MainActivity.this, MineActivity.class), 100);
                    drawer.closeDrawer(GravityCompat.START);
                }
            }
        });
        if (preferences.getString("status", "").equals("3")) {
            initLeft();
        }
//        leftlv.addHeaderView(head);
        addheadview.addView(head);
        leftlv.setAdapter(leftItemAdapter);
        leftlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                if (i == 0) {//头部点击
//                    return;
//                }
//                if (i == leftItemAdapter.getCount() - 1) {//头部点击
////                    toastShow("zuihou");
//                    //  return;
//                }
                if (!islogin) {
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
                    drawer.closeDrawer(GravityCompat.START);
                } else {
                    Intent intent = null;
                    TextView textView = (TextView) view.findViewById(R.id.tv_left_name);
                    if (textView.getText().toString().equals("我的行程")) {
                        intent = new Intent(MainActivity.this, MyJourneyActivity.class);
                    } else if (textView.getText().toString().equals("我的钱包")) {
                        intent = new Intent(MainActivity.this, MyWalletActivity4.class);
                        intent.putExtra("shengche20", huodongdanche20);
                        intent.putExtra("chong20", (Serializable) imagesBeen);
                        intent.putExtra("hasbuy20danche", hasbuy20danche);
//                        intent = new Intent(MainActivity.this, MyWalletActivity3.class);
                    } else if (textView.getText().toString().equals("我的单车")) {
//                        intent = new Intent(MainActivity.this, MyBikeActivity3.class);
                        intent = new Intent(MainActivity.this, MybikeActivity6.class);
//                            intent = new Intent(MainActivity.this, MyBikeActivity.class);
                    } else if (textView.getText().toString().equals("邀请分享")) {
                        intent = new Intent(MainActivity.this, MyShareMsgActivity3.class);
                        //     intent = new Intent(MainActivity.this, MyShareMsgActivity.class);
                    } else if (textView.getText().toString().equals("设置")) {
                        startActivityForResult(new Intent(MainActivity.this, MineActivity.class), 100);
                        drawer.closeDrawer(GravityCompat.START);
                        return;
                    } else if (textView.getText().toString().equals("我要举报")) {
                        intent = new Intent(MainActivity.this, JvBaoActivity.class);
                    } else if (textView.getText().toString().equals("使用指南")) {
                        intent = new Intent(MainActivity.this, ZhiNanActivity.class);
                    } else if (textView.getText().toString().equals("翼活动")) {
                        intent = new Intent(MainActivity.this, YihuodongActivity4.class);
                    } else if (textView.getText().toString().equals("单车合伙人")) {
                        intent = new Intent(MainActivity.this, DanchehehuorenxiangqingActivity.class);
                    } else if (textView.getText().toString().equals("城市合伙人")) {
                        if (ischenghsihehuoren)//合伙人
                        {
                            intent = new Intent(MainActivity.this, ChengshihehuorenActivity.class);
                            startActivityForResult(intent, 10000);
                            drawer.closeDrawer(GravityCompat.START);
                            return;
                        }
//                        else if (iszhunhehuoren)//准合伙人
//                        {
//                            intent = new Intent(MainActivity.this, ZhunhehuorenActivity.class);
//                            startActivityForResult(intent, 10000);
//                            drawer.closeDrawer(GravityCompat.START);
//                            return;
//                        }
                        else {
                            intent = new Intent(MainActivity.this, ChengshihehuorenxiangqingActivity.class);
                            startActivityForResult(intent, 10000);
                            drawer.closeDrawer(GravityCompat.START);
                            return;
                        }
                    } else {
                        return;
                    }
                    startActivityForResult(intent, 10000);
                }
                drawer.closeDrawer(GravityCompat.START);
            }
        });
    }

    private String startplantnum;
    String deviceId;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 1) {
            islogin = true;
            try {
                setAlias(this, preferences.getString("mobile", ""), null);
            } catch (Exception e) {
                e.printStackTrace();
                setAlias(this, "", null);
            }
            reloadAccountInfo();
            has20danche();
//            getSettings();
        } else if (requestCode == 100 && resultCode == 2) {
            try {
                setAlias(this, "", null);
            } catch (Exception e) {
                setAlias(this, "", null);
            }
            ll_state.setVisibility(View.GONE);
            iv_morelogin.setVisibility(View.GONE);
            try {
                ischenghsihehuoren = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
            tvname.setText("请登录");
            left_userIcon.setImageResource(R.mipmap.head_moren);
            islogin = false;
            iv_scan.setEnabled(true);
            iv_scan.setVisibility(View.VISIBLE);
            iv_tel.setEnabled(true);
            iv_tel.setVisibility(View.VISIBLE);
            ivdongjie.setVisibility(View.INVISIBLE);
            tvdongjie.setVisibility(View.INVISIBLE);
            if (window != null) {
                window.setHeight(0);
            }
        } else if (requestCode == 5000 && resultCode == RESULT_OK) {//扫描结果
            /*
            mac=data.getStringExtra(CaptureActivity.EXTRA_BITMAP);
            Intent bindIntent = new Intent(this, LockService.class);
            bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
            */
            ////    startplantnum = data.getStringExtra(CaptureActivity.EXTRA_RESULT);
            ////    deviceId = startplantnum;
            ////    mac = data.getStringExtra(CaptureActivity.EXTRA_BITMAP);
//            if(Config.DEBUG){
//                toastShow("测试计费");
//            }else{
            ////     tzfuq();
//            }

//            startfirst();

        } else if (requestCode == 5000 && resultCode == 1) {//手动结果
//            startplantnum = "http://p.zhouyibike.com/" + data.getStringExtra(CaptureActivity.EXTRA_RESULT);
//            startfirst();
        } else if (requestCode == 10000 && resultCode == 1) {//跟钱有关  要重新获取用户余额  看是否余额小于最低数
            //重新获取用户信息
            reloadAccountInfo();
        } else if (requestCode == 10001 && resultCode == 1) {//跟钱有关  要重新获取用户余额  看是否余额小于最低数
            //重新获取用户信息
            shouldshowending = false;
            if (window != null) {
                window.dismiss();
            }
            if (window != null) {
                window.dismiss();
            }
            if (window != null) {
                window.dismiss();
            }
            iv_scan.setEnabled(true);
            iv_scan.setVisibility(View.VISIBLE);
            iv_tel.setEnabled(true);
            iv_tel.setVisibility(View.VISIBLE);
            reloadAccountInfo();
        } else if (requestCode == 1020 && resultCode == 20) {//成功购机买20单车后
            //是否购买过20信息
            has20danche();
        } else if (requestCode == 123 && resultCode == 123) {
            //是否用户冻结
            //重新获取用户信息
            if (window.isShowing()) {
                window.dismiss();
                window.setHeight(0);
//                window.c
//                window=null;
            }
            reloadAccountInfo();
        } else if (requestCode == 1288 && resultCode == 1288) {
            hasbuy20danche = true;
        } else if (requestCode == 208 && resultCode == 123) {
            //是否用户冻结
            //重新获取用户信息
            if (window.isShowing()) {
                window.dismiss();
                window.setHeight(0);
//                window.c
//                window=null;
            }
            reloadAccountInfo();
        }
        if (resultCode == 2501)//需重新登录
        {
            startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
        }
    }

    /**
     * 开始行程前准备工作
     */
    private void startfirst() {
        if (startplantnum.equals("") || !startplantnum.startsWith("http://p.zhouyibike.com/")) {
            toastShow("扫描失败!");
        } else {
            //这里等服务器接口协议出来后，需要修改为使用result向网络请求Ble的地址待返回后再启动新的activity
            try {
//                toastShow("扫描成功!");
                deviceId = startplantnum.replace("http://p.zhouyibike.com/", "");
                getMac(deviceId);
            } catch (Exception e) {
                toastShow("二维码错误!");
            }
        }
    }

    //========================================service start
//    private LockService mService = null;
//    private ServiceConnection mServiceConnection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
//            Log.e("service", "start");
//            mService = ((LockService.LocalBinder) rawBinder).getService();
//            if (!mService.initialize(mOnBleCallback, Config.custom_id)) {
//                finish();
//            }
//
//
//            if ((mac != null)) {
//                if (mService.connect(mac)) {
//                    toastShow("连接下一步 ");
//                } else {
//                    toastShow("连接失败");
//                    unbindService(mServiceConnection);
//                    mService.stopSelf();
//                    mService = null;
//                }
//            }
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName classname) {
//            mService = null;
//        }
//    };
//    private LockService.OnBleCallback mOnBleCallback = new LockService.OnBleCallback() {
//        @Override
//        public void onConnected() {
//            toastShow("设备已经连接");
//        }
//
//        public void onDisconnected() {
//            toastShow("蓝牙连接失败,正在重试");
//            mService.connect(mac);
////            try {
////                unbindService(mServiceConnection);
////                mService.stopSelf();
////                mService = null;
////            }catch (Exception e){
////
////            }
//        }
//
//        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
//        @Override
//        public void onDeviceReady(LockService.BleInfo info) {
//            toastShow("开始开锁");
//            //开锁id
//            // mService.openLock(deviceId, 0000);
//            mService.openLock(deviceId, 0311);
//        }
//
//        @Override
//        public void onOpenLock(int result, Date var2) {
//            if (result == 0) {
////                toastShow("开锁成功");
////                tzfuq();
//                if (hastongzhi)
//                {
//                    tzfuq();
//                    hastongzhi=false;
//                }
//            } else {
//                toastShow("开锁失败");
//            }
//            try {
//                unbindService(mServiceConnection);
//                mService.stopSelf();
//                mService = null;
//            } catch (Exception e) {
//
//            }
//        }
//
//        @Override
//        public void onCloseLock(int var1, long var2, Date var4) {
//
//        }
//
//    };

    /**
     * 通知服务器开锁成功
     */
    private void tzfuq() {
//        toastShow("通知服务器开锁成功");
        if (hastongzhi) {
            hastongzhi = false;
            Map<String, String> params = new HashMap<>();
            params.put("token", preferences.getString("token", ""));
            params.put("plateNumber", deviceId);
            params.put("mac", mac);
            params.put("longitude", mylng + "");
            params.put("latitude", mylat + "");
//        showProgressDialog();
            addSubscription(apiStores.OpenByBluetooth(params),
                    new ApiCallback<KaiSuoResult>() {
                        @Override
                        public void onSuccess(KaiSuoResult model) {
                            if (model.getStatus() == Config.SUCCESSCODE) {
//                            Intent intent=new Intent(MainActivity.this,RaidingActivity.class);
//                            intent.putExtra("bikenum",deviceId);
//                            intent.putExtra("money_unit",money_unit);
//                            startActivityForResult(intent,10000);
                                hasshowendinfo = false;
                                SharedPreferences.Editor edit = preferences.edit();
                                edit.putFloat("qixingjuli", 0f);
                                edit.commit();
                                qixingjuli = 0;
                                qixingreliang = 0;
                                hf = 0;
                                hb = 0;
                                mf = 0;
                                mb = 0;
                                sf = 0;
                                sb = 0;
                                isriding = true;
                                showdrivingpop();
                                setdrivinginfo(model);
                                drivefar.setText(qixingjuli + "米");
                                drivehot.setText(qixingreliang + "大卡");
                                try {
                                    if (myhandlertime != null) {
                                        myhandlertime.removeMessages(1);
                                    }
                                    if (myhandlertime==null)
                                    {
                                        myhandlertime = new Myhandlertime();
                                    }
                                    myhandlertime.sendEmptyMessageDelayed(1, 1000);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                toastShow(model.getMessage());
                            }
                        }

                        @Override
                        public void onFailure(String msg) {
                            toastShow(msg);
                            hastongzhi = true;
                        }

                        @Override
                        public void onFinish() {
//                        dismissProgressDialog();
                            Log.e("onFinish: ", "信号");
                        }
                    });
        }
    }

    //========================================service end
    String mac = "";

    private void getMac(String deviceId) {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("plateNumber", deviceId);
        showProgressDialog();
        addSubscription(apiStores.GetMac(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
//                            toastShow("获取mac成功");
                            mac = model.getData();
                            StringBuilder sb = new StringBuilder(mac);
                            sb.insert(10, ":");
                            sb.insert(8, ":");
                            sb.insert(6, ":");
                            sb.insert(4, ":");
                            sb.insert(2, ":");
                            mac = sb.toString();
//                            tzfuq();
//                            currentDevice = mBluetoothAdapter.getRemoteDevice(mac);
//                            Intent bindIntent = new Intent(MainActivity.this, LockService.class);
//                            bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    /**
     * 重新获取用户信息数据
     */
    private void reloadAccountInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("token",preferences.getString("token", ""));
        Log.e("reloadAccountInfo: ",preferences.getString("token", "") );
        //   showProgressDialog();
        addSubscription(apiStores.ReloadAccountInfo(params),
                new ApiCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            if (model.getData().getStatus().equals("3")) {
                                getSettings();
                                tvdongjie.setVisibility(View.INVISIBLE);
                                ivdongjie.setVisibility(View.INVISIBLE);
                                iv_scan.setVisibility(View.VISIBLE);
                                if (window != null) {
                                    window.setHeight((int) (getScreenh(MainActivity.this) * 0.35));
                                }
                            } else if (model.getData().getStatus().equals("11")) {
                                //冻结
                                //   dismissProgressDialog();
                                {
                                    tvdongjie.setVisibility(View.VISIBLE);
                                    ivdongjie.setVisibility(View.VISIBLE);
                                    iv_scan.setVisibility(View.INVISIBLE);
                                    if (window != null) {
                                        window.setHeight((int) (0));
                                    }
                                }
                            }
                            try {
                                ischenghsihehuoren=model.getData().isCityCompany;
                            } catch (Exception e) {
                                e.printStackTrace();
                                ischenghsihehuoren=false;
                            }
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putString("token", model.getData().getToken());
                            edit.putString("fullName", model.getData().getFullName());
                            edit.putString("headPicture", model.getData().getHeadPicture());
                            edit.putString("nickName", model.getData().getNickName());
                            edit.putString("status", model.getData().getStatus());
                            if (model.getData().getStatus().equals("11") || model.getData().getStatus().equals("3")) {
                                edit.putString("status", "3");
                            }
                            edit.putString("createTime", model.getData().getCreateTime());
                            edit.putBoolean("hasPassword", model.getData().isHasPassword());
                            edit.putString("lastLoginTime", model.getData().getLastLoginTime());
                            edit.putString("minAmountForRiding", model.getData().getMinAmountForRiding());
                            edit.putString("rechargeAmount", model.getData().getRechargeAmount());
                            edit.putString("incomeAmount", model.getData().getIncomeAmount());
                            edit.putString("totalAmount", model.getData().getTotalAmount());
                            edit.commit();
                            if (Double.parseDouble(model.getData().getTotalAmount()) < minmoneyforriding) {
                                //弹出余额少对话框
                                initDailog(3);
                                if (!yzmdialog.isShowing()) {
                                    yzmdialog.show();
                                }
                            }
                        }
//                        else if (model.getStatus() == 508 || model.getStatus() == 506 || model.getStatus() == 307) {
//                            //需重新登录
//                            startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
//                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        initLeft();
                    }
                });
    }

    /**
     * 开始行程
     */
    private void startRiding() {
        StartRidingInfo startRiding = new StartRidingInfo();
        startRiding.setToken(preferences.getString("token", ""));
        StartRidingInfo.DataBean sdb = new StartRidingInfo.DataBean();
        sdb.setPlateNumber(deviceId);
        sdb.setLatitude(mylat);
        sdb.setLongitude(mylng);
        startRiding.setModel(sdb);
        addSubscription(apiStores.StartRiding(startRiding),
                new ApiCallback<StartRidingResult>() {

                    @Override
                    public void onSuccess(StartRidingResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
//                            Intent intent=new Intent(MainActivity.this,RaidingActivity.class);
//                            intent.putExtra("bikenum",startplantnum);
////                            intent.putExtra("bicycleId",model.getData().getBicycleId());
//                            intent.putExtra("money_unit",money_unit);
//                            startActivityForResult(intent,10000);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                    }
                });

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                if (shouldshowending) {
                    if (window.isShowing()) {
                        window.dismiss();
                    }
                }
                drawer.openDrawer(GravityCompat.START);
                break;
            case R.id.imageView4://打电话
//                teldialog.show();
//                Intent intentjubao = new Intent(MainActivity.this, JvBaoActivity.class);
//                startActivityForResult(intentjubao, 10000);
//                jubaodialog.show();
                if (islogin) {
                    canjubao();
                } else {
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
                }
//                Uri uri = Uri.parse("tel:" + Config.TEL);
//                Intent intenttel = new Intent(Intent.ACTION_DIAL, uri);
//                startActivity(intenttel);
                break;
            case R.id.bmapView:
                if (ll_yydc.getVisibility() == View.VISIBLE) {
                    ll_yydc.setVisibility(View.GONE);
                }
                break;
            case R.id.iv_map_mylocation:
//                centerlng = 0.0;
//                centerlat = 0.0;
//                LatLng ll = new LatLng(mylat, mylng);
//                MapStatus.Builder builder = new MapStatus.Builder();
//                builder.target(ll).zoom(17.0f);
//                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                centerlng = mylng;
                centerlat = mylat;
                zoomanim(mylat, mylng);
                break;
            case R.id.ll_main_chong20songdanche://充20送单车
                if (islogin) {
                    chong20();
                } else {
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
                }

                break;
            case R.id.iv_map_refresh:
                if (isyysuccess) {
                    return;
                }
                isshuaxin = true;
                //  firstanim=true;
                iv_refresh.setEnabled(false);
                iv_refresh.startAnimation(operatingAnim);
                operatingAnim.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        iv_refresh.clearAnimation();
                        iv_refresh.setVisibility(View.INVISIBLE);
                        iv_refresh.setEnabled(true);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
//                if (centerlng != 0) {
//                    findBictcleByRange(2);
//                } else {
//                    findBictcleByRange(1);
//                }
                zoomanim(0, 0);
                break;
            case R.id.btn_yuyuepop_start://预约单车
                if (islogin) {
                    if (!ishaveenoughmoney(true)) {
                        bookingRiding();
                    }
                } else {
                    ll_yydc.setVisibility(View.GONE);
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
                }
                break;
            case R.id.btn_yuyuepop_success_cancle://取消预约
                endBookingRiding();
                break;
            case R.id.huodongmaduihuan://活动码充值20单车
                drawer.closeDrawer(GravityCompat.START);
                // startActivityForResult(new Intent(MainActivity.this, HuodongduihuanActivity.class), 120);
                if (islogin) {
                    youhuihuodongma();
                } else {
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
                }
                break;
//            huodongmaduihuan
            case R.id.iv_mian_scan://扫码租车
                if (islogin) {
                    isfirstkaisuo();
//                    if (!ishaveenoughmoney(true)) {
//                        if (checkly()) {
//                            if (PermissionTool.isCameraCanUse()) {
//                                Intent intent = new Intent(MainActivity.this, DeviceScanActivity.class);
//                                intent.putExtra("latu", mylat);
//                                intent.putExtra("long", mylng);
////                            Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
//                                // Intent intent = new Intent(MainActivity.this, NewScanActivity.class);
//                                startActivityForResult(intent, 5000);
//                            } else {
//                                toastShow("没有获取相机权限,请手动设置应用权限");
//                            }
//                            break;
//                        } else {
//                            toastShow("打开蓝牙失败,请手动打开蓝牙");
//                            startAppSettings();
//                            break;
//                        }
//                        //扫码界面
//
//                    }
                } else {
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), 100);
                }
                break;
        }
    }

    private void openBLE() {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(intent);
        }
    }

    boolean isScanning = false;

    private void scanBLE() {


        if (mBluetoothAdapter == null) {
            toastShow("设备不支持BLE");
            return;
        }

        openBLE();

        if (!isScanning) {
            isScanning = true;
            mBluetoothAdapter.startLeScan(uuids, mLeScanCallback);
        }

    }

    private void stopScan() {
        if (isScanning) {
            isScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (!mLeDevices.contains(device)) {
                mLeDevices.add(device);

//                MLog.i("LockService", "name: " + device.getName() + "\tmac: " + device.getAddress());

            }

            if (null != currentDevice && mLeDevices.contains(currentDevice)) {
                stopScan();
            }
        }
    };

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private boolean checkly() {

//        if (mBluetoothManager == null) {
//            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
//            if (mBluetoothManager == null) {
//                return false;
//            }
//        }
//        mBluetoothAdapter = mBluetoothManager.getAdapter();
//        if (mBluetoothAdapter == null) {
//            return false;
//
//        }
//        if(!mBluetoothAdapter.isEnabled()){
//            mBluetoothAdapter.enable();
//        }
        return true;
    }

    private void endBookingRiding() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("plateNumber", endnum);
        showProgressDialog();
        addSubscription(apiStores.EndBookingRiding(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            isyysuccess = false;
                            ll_yydc_succ.setVisibility(View.GONE);
                            iv_center.setVisibility(View.VISIBLE);
                            try {
                                initMarket2();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    /**
     * 获取预约时限
     */
    private double minmoneyforriding;//账号最少钱数

    private void getSettings() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.GetSettings(params),
                new ApiCallback<SettingResult>() {

                    @Override
                    public void onSuccess(SettingResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putString("bicyclePrice", model.getData().getBicyclePrice() + "");
                            edit.putString("bookingMinutes", model.getData().getBookingMinutes() + "");
                            edit.putString("minAmountForRiding", model.getData().getMinAmountForRiding() + "");
                            edit.putString("money_unit", model.getData().getRidingPrice() + "");
                            minmoneyforriding = Double.parseDouble(model.getData().getMinAmountForRiding());
                            maxmin = model.getData().getBookingMinutes();
                            money_unit = model.getData().getRidingPrice();
                            edit.commit();
                            hasBooking();
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                    }
                });
    }

    /**
     * 获取当前行程
     */
    private void myRiding() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.MyRiding(params),
                new ApiCallback<MyRidingResult>() {

                    @Override
                    public void onSuccess(MyRidingResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            if (model.getData().getStatus() == 1) {
                                //预约
                                endnum = model.getData().getPlateNumber();
                                endlat = model.getData().getLatitude();
                                endlng = model.getData().getLongitude();
                                try {
                                    timehapast = (TimeUtils.getCurrentTimeInLong() - TimeUtils.stringToLong(model.getData().getStartTime(), "yyyy-MM-dd HH:mm")) / 1000;
                                    maxmin = maxmin - (int) (timehapast / 60);
                                    maxsec = (int) (timehapast % 60);
                                } catch (Exception e) {
                                }
                                myhandler.sendEmptyMessage(4);
                            } else if (model.getData().getStatus() == 10) {//骑行中
                                try {
                                    timehapast = (TimeUtils.getCurrentTimeInLong() - TimeUtils.stringToLong(model.getData().getStartTime(), "yyyy-MM-dd HH:mm")) / 1000;
                                } catch (Exception e) {
                                    timehapast = 0L;
                                }
//                                Intent intent=new Intent(MainActivity.this,RaidingActivity.class);
//                                intent.putExtra("bikenum",model.getData().getPlateNumber());
//                                intent.putExtra("bicycleId",model.getData().getBicycleId());
//                                intent.putExtra("money_unit",money_unit);
//                                if(timehapast!=0){
//                                    intent.putExtra("timepast",timehapast);
//                                }
//                                startActivityForResult(intent,10000);
                                isriding = true;
                                hasshowendinfo = false;
//                                qixingjuli=0;
//                                qixingreliang=0;
//                                hf=0;hb=0;mf=0;mb=0;sf=0;sb=0;
                                showdrivingpop();
                                setdrivinginfo(model);
                                try {
                                    if (myhandlertime != null) {
                                        myhandlertime.removeMessages(1);
                                    }
                                    if (myhandlertime==null)
                                    {
                                        myhandlertime = new Myhandlertime();
                                    }
                                    myhandlertime.sendEmptyMessageDelayed(1, 1000);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                    }
                });
    }

    /**
     * 27. 是否有未结束行程
     */
    private void hasRiding() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.HasRiding(params),
                new ApiCallback<BookingResult>() {

                    @Override
                    public void onSuccess(BookingResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            isriding = model.isData();
                            if (model.isData()) {
                                myRiding();
                            } else {
                                getUnpaidOrder();
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                    }
                });
    }

    /**
     * 是否认证等  是否余额不足
     */
    private boolean ishaveenoughmoney(boolean isshow) {
        if (preferences.getString("status", "").equals("0")) {
            tvstate.setText("未认证");
            iv_state.setImageResource(R.drawable.info_weiyirenzheng);
            if (isshow) {
                initDailog(2);
                if (!yzmdialog.isShowing()) {
                    yzmdialog.show();
                }
                return true;
            } else {
                startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                return true;
            }
        } else if (preferences.getString("status", "").equals("1")) {
            tvstate.setText("未认证");
            iv_state.setImageResource(R.drawable.info_weiyirenzheng);
            if (isshow) {
                initDailog(1);
                if (!yzmdialog.isShowing()) {
                    yzmdialog.show();
                }
                return true;
            } else {
                startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                return true;
            }
        } else if (preferences.getString("status", "").equals("3")) {
            tvstate.setText("已认证");
            iv_state.setImageResource(R.drawable.info_yirenzheng);
            if (isshow) {
                if (Double.parseDouble(preferences.getString("totalAmount", "0")) < minmoneyforriding) {
                    //弹出余额少对话框
                    initDailog(3);
                    if (!yzmdialog.isShowing()) {
                        yzmdialog.show();
                    }
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * chong20活动
     */
    private boolean chong20() {
        if (preferences.getString("status", "").equals("0")) {
            tvstate.setText("未认证");
            iv_state.setImageResource(R.drawable.info_weiyirenzheng);
            if (true) {
                initDailog(2);
                if (!yzmdialog.isShowing()) {
                    yzmdialog.show();
                }
                return true;
            } else {
                startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                return true;
            }
        } else if (preferences.getString("status", "").equals("1")) {
            tvstate.setText("未认证");
            iv_state.setImageResource(R.drawable.info_weiyirenzheng);
            if (true) {
                initDailog(1);
                if (!yzmdialog.isShowing()) {
                    yzmdialog.show();
                }
                return true;
            } else {
                startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                return true;
            }
        } else if (preferences.getString("status", "").equals("3")) {
            if (!hasbuy20danche) {
                Intent intentchong20 = new Intent(MainActivity.this, PayActivity20.class);
//                        huodongdanche20
                intentchong20.putExtra("shengche20", huodongdanche20);
                intentchong20.putExtra("chong20", (Serializable) imagesBeen);
                startActivityForResult(intentchong20, 1020);//充20活动
            } else {
//                toastShow("你已经买了20单车了");
//                Intent intentchong20 = new Intent(MainActivity.this, PayActivity20.class);
//                intentchong20.putExtra("shengche20",huodongdanche20);
//                intentchong20.putExtra("chong20", (Serializable) imagesBeen);
//                startActivityForResult(intentchong20, 1020);//充20活动
                Intent i = new Intent(this, Buy20SuccessActivity.class);
                i.putExtra("shengche20", huodongdanche20);
                i.putExtra("chong20", (Serializable) imagesBeen);
                startActivity(i);
            }
        }
        return false;
    }

    /**
     * 优惠活动
     */
    private boolean youhuihuodongma() {
        if (preferences.getString("status", "").equals("0")) {
            tvstate.setText("未认证");
            iv_state.setImageResource(R.drawable.info_weiyirenzheng);
            if (true) {
                initDailog(2);
                if (!yzmdialog.isShowing()) {
                    yzmdialog.show();
                }
                return true;
            } else {
                startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                return true;
            }
        } else if (preferences.getString("status", "").equals("1")) {
            tvstate.setText("未认证");
            iv_state.setImageResource(R.drawable.info_weiyirenzheng);
            if (true) {
                initDailog(1);
                if (!yzmdialog.isShowing()) {
                    yzmdialog.show();
                }
                return true;
            } else {
                startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                return true;
            }
        } else if (preferences.getString("status", "").equals("3")) {
            {
                Intent i = new Intent(this, HuodongduihuanActivity.class);
                i.putExtra("shengche20", huodongdanche20);
                i.putExtra("chong20", (Serializable) imagesBeen);
                startActivityForResult(i, 1288);
            }
        }
        return false;
    }

    /**
     * 举报
     */
    private boolean canjubao() {
        if (preferences.getString("status", "").equals("0")) {
            tvstate.setText("未认证");
            iv_state.setImageResource(R.drawable.info_weiyirenzheng);
            if (true) {

                initDailog(2);
                if (!yzmdialog.isShowing()) {
                    yzmdialog.show();
                }
                return true;
            } else {
                startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                return true;
            }
        } else if (preferences.getString("status", "").equals("1")) {
            tvstate.setText("未认证");
            iv_state.setImageResource(R.drawable.info_weiyirenzheng);
            if (true) {
                initDailog(1);
                if (!yzmdialog.isShowing()) {
                    yzmdialog.show();
                }
                return true;
            } else {
                startActivityForResult(new Intent(MainActivity.this, YanzhengActivity.class), 100);
                return true;
            }
        } else if (preferences.getString("status", "").equals("3")) {
            jubaodialog.show();
        }
        return false;
    }

    /**
     * 获取未完成订单列表
     */
    private void getUnpaidOrder() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.GetUnpaidOrderForPay(params),
                new ApiCallback<OrderUnPayNewResult>() {

                    @Override
                    public void onSuccess(OrderUnPayNewResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {

                            if (model.getData().size() > 0) {
                                if (model.getData().get(0).getType() == 4) {

                                } else {
                                    Intent intent = new Intent(MainActivity.this, RaidingEndActivity.class);
                                    intent.putExtra("msg", model.getData().get(0));
                                    startActivityForResult(intent, 10000);
                                }
                            } else {
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                    }
                });
    }

    /**
     * 是否有预约车辆
     */
    private void hasBooking() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.HasBooking(params),
                new ApiCallback<BookingResult>() {

                    @Override
                    public void onSuccess(BookingResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            isyysuccess = model.isData();
                            if (isyysuccess) {
                                myRiding();
                            } else {
                                hasRiding();
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                    }
                });
    }

    /**
     * 定位SDK监听函数
     */
    boolean isFirstLoc = true; // 是否首次定位

    //路径规划相关=======================================================================================start
    private class MyDrivingRouteOverlay extends WalkingRouteOverlay {
        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public int getLineColor() {
            return getResources().getColor(R.color.color_ljgh);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            //自定义的起点图标
            return BitmapDescriptorFactory.fromResource(R.mipmap.point);
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            //自定义的终点图标
            return BitmapDescriptorFactory.fromResource(R.mipmap.point);
        }

        @Override
        public BitmapDescriptor getNoteMarker() {
            //自定义的终点图标
            return BitmapDescriptorFactory.fromResource(R.mipmap.note_point);
        }

    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
        // 获取步行线路规划结果
        if (walkingRouteResult == null || walkingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
            toastShow("抱歉，路径规划错误");
        }
        if (walkingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            toastShow("抱歉，路径规划错误");
            return;
        }
        if (walkingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            WalkingRouteLine walkingRouteLine = walkingRouteResult.getRouteLines().get(0);
            distence = walkingRouteLine.getDistance() + "";
            usetime = walkingRouteLine.getDuration() / 60 + "";
            this.walkingRouteResult = walkingRouteResult;
            //翻编获取详细地址
            mSearchgc.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(endlat, endlng)));
            mSearchgc.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                @Override
                public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

                }

                @Override
                public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                    userlocation = reverseGeoCodeResult.getAddress();
                    if (isyysuccess) {
                        showSuccessPopupWindow();
                    } else {
                        showPopupWindow();
                    }
                    myhandler.sendEmptyMessageDelayed(3, 300);
                }
            });


        }
    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }
    //路径规划相关=======================================================================================end

    /**
     * 我的位置
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            if (location == null || mMapView == null) {
                return;
            }
            mCurrentAccracy = location.getRadius();
            LatLng p1LL = new LatLng(location.getLatitude(), location.getLongitude());
            LatLng p2LL = new LatLng(mylat, mylng);
            //  LatLng p2LL = new LatLng(mylat+(0.001), mylng);
            double distance = DistanceUtil.getDistance(p1LL, p2LL);
            if (isriding) {
                Log.e("onReceiveLocation: ", mylat + "+++" + mylng + "+++" + location.getLatitude() + "+++" + location.getLongitude() + "+++" + distance);
                if (distance < 1000 && distance > 10) {
                    qixingjuli += distance;
                    SharedPreferences.Editor edit = preferences.edit();
                    edit.putFloat("qixingjuli", (float) qixingjuli);
                    edit.commit();
                    qixingreliang = qixingjuli * 60 * 1.05 * 0.001;
                }
            }
            mylat = location.getLatitude();
            mylng = location.getLongitude();
            MyApplication.getInstances().setLat(mylat);
            MyApplication.getInstances().setLng(mylng);
            Log.e("lyl", mylat + "==" + mylng);
            MyLocationData locData = new MyLocationData.Builder()
//                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude()).longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;
                /**
                 * 地图定位到当前位置
                 */
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(17.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                if (ll_yydc.getVisibility() != View.VISIBLE)
                    myhandler.sendEmptyMessageDelayed(1, 1000);
            }
            if (!islocation) {
                islocation = true;
                myhandler.sendEmptyMessage(4);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }

        public void onConnectHotSpotMessage(String s, int i) {

        }
    }

    @Override
    public void onBackPressed() {
        if (ll_yydc.getVisibility() == View.VISIBLE) {
            ll_yydc.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 初始化方向传感器
     */
    private void initOritationListener() {
        myOrientationListener = new MyOrientationListener(
                getApplicationContext());
        myOrientationListener
                .setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
                    @Override
                    public void onOrientationChanged(float x) {
                        mXDirection = (int) x;

                        // 构造定位数据
                        MyLocationData locData = new MyLocationData.Builder()
                                //    .accuracy(mCurrentAccracy)
                                // 此处设置开发者获取到的方向信息，顺时针0-360
                                .direction(mXDirection)
                                .latitude(mylat)
                                .longitude(mylng).build();
                        // 设置定位数据
                        mBaiduMap.setMyLocationData(locData);
                        // 设置自定义图标
                        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                                .fromResource(R.mipmap.fangxiang_loc);
                        mBaiduMap.setMyLocationData(locData);
                        MyLocationConfiguration config = new MyLocationConfiguration(
                                MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker);
                        mBaiduMap.setMyLocationConfigeration(config);

                    }
                });
    }


    /**
     * 定位信息
     */
    private void locationmsg() {
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);
        //点击获取路径规划      lylmarketclick
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
//                myhandler.removeMessages(2);
//                if(isyysuccess){
//                    return false;
//                }
//                PlanNode stNode = PlanNode.withLocation(new LatLng(mylat,mylng));
//                PlanNode enNode = PlanNode.withLocation(new LatLng(marker.getPosition().latitude,marker.getPosition().longitude));
//                endlat=marker.getPosition().latitude;
//                endlng=marker.getPosition().longitude;
//                endnum=marker.getTitle();
//                InfoWindow mInfoWindow = null;
//                //生成一个TextView用户在地图中显示InfoWindow
//                TextView location = new TextView(getApplicationContext());
//                location.setBackgroundResource(R.drawable.littlecircle);
//                location.setPadding(30, 30, 30, 30);
//                location.setText(endnum+"");
//                //将marker所在的经纬度的信息转化成屏幕上的坐标
//                final LatLng ll = marker.getPosition();
//                Point p = mBaiduMap.getProjection().toScreenLocation(ll);
//                p.y -= 120;
//                LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);
//                //显示InfoWindow
//                mInfoWindow =new InfoWindow(location,llInfo,0);
//                mBaiduMap.showInfoWindow(mInfoWindow);
//                initMarket();
//                mSearch.walkingSearch(new WalkingRoutePlanOption().from(stNode).to(enNode));
                return false;
            }
        });

        //地图状态监听
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {

            @Override
            public void onMapStatusChangeStart(MapStatus arg0) {
                // 手势操作地图，设置地图状态等操作导致地图状态开始改变。
//                myhandler.removeMessages(1);
//                myhandler.removeMessages(2);
                zoomnum = arg0.zoom;
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
                ll_fjwdc.setVisibility(View.GONE);
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus arg0) {
                float zoom = arg0.zoom;
//                if(Math.abs(zoomnum-zoom)> 0.001){
//                    zoomnum =zoom;
//                    Log.e("zoom","缩放起了变化，现在缩放等级为"+zoom);
//                }else{
                // 地图状态改变结束
                //target地图操作的中心点。
                LatLng target = mBaiduMap.getMapStatus().target;
                Log.e("lyl", "中心点" + target.latitude + "===" + target.longitude);
                centerlat = target.latitude;
                centerlng = target.longitude;
                LatLng p1LL = new LatLng(centerlat, centerlng);
                LatLng p2LL = new LatLng(shuaxinlat, shuaxinlng);
                double distance = DistanceUtil.getDistance(p1LL, p2LL);
                if (distance > 1200) {
                    if (iv_refresh.getVisibility() == View.VISIBLE) {
                        shuaxinlng = centerlng;
                        shuaxinlat = centerlat;
                        return;
                    }
                    if (isshuaxining) {
                        iv_refresh.setVisibility(View.INVISIBLE);
                    } else {
                        iv_refresh.setVisibility(View.VISIBLE);
                    }

                    if (isshuaxin) {
                        isshuaxin = false;
                        iv_refresh.clearAnimation();
                        iv_refresh.setVisibility(View.INVISIBLE);
                    }
                }

                Log.e("onMapStatu: ", "" + distance);
                // myhandler.sendEmptyMessageDelayed(2, 1000);
//                }
            }
        });
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        // option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(3000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * 发起预约
     */
    private void bookingRiding() {
        YuYueInfo yyinfo = new YuYueInfo();
        YuYueInfo.DataBean udb = new YuYueInfo.DataBean();
        yyinfo.setToken(preferences.getString("token", ""));
        udb.setLongitude(endlng + "");
        udb.setLatitude(endlat + "");
        udb.setPlateNumber(endnum);
        yyinfo.setModel(udb);
        showProgressDialog();
        addSubscription(apiStores.BookingRiding(yyinfo),
                new ApiCallback<YuYueResult>() {

                    @Override
                    public void onSuccess(YuYueResult model) {

                        if (model.getStatus() == Config.SUCCESSCODE) {
                            initresultDailog(true, "预约成功", "我们为您保留15分钟，请尽快使用");
                            isyysuccess = true;
                            ll_yydc.setVisibility(View.GONE);
                            iv_center.setVisibility(View.VISIBLE);
                            resultdialog.show();
                        } else if (model.getStatus() == 0) {// 0 请激活你的账户 1 请实名认证 3 余额不足,请充值
                            initDailog(2);
                            ll_yydc.setVisibility(View.GONE);
                            iv_center.setVisibility(View.VISIBLE);
                            if (!yzmdialog.isShowing()) {
                                yzmdialog.show();
                            }
                        } else if (model.getStatus() == 1) {
                            initDailog(1);
                            ll_yydc.setVisibility(View.GONE);
                            iv_center.setVisibility(View.VISIBLE);
                            if (!yzmdialog.isShowing()) {
                                yzmdialog.show();
                            }
                        } else if (model.getStatus() == 202) {
                            ll_yydc.setVisibility(View.GONE);
                            iv_center.setVisibility(View.VISIBLE);
                            initresultDailog(false, "该车已被预约", "请您选择其他车辆骑行,谢谢");
                            resultdialog.show();
                        } else if (model.getStatus() == 102) {
                            ll_yydc.setVisibility(View.GONE);
                            iv_center.setVisibility(View.VISIBLE);
                            initresultDailog(false, "单车预约中", "请您选择其他车辆骑行,谢谢");
                            resultdialog.show();
                        } else if (model.getStatus() == 101) {
                            ll_yydc.setVisibility(View.GONE);
                            iv_center.setVisibility(View.VISIBLE);
                            initresultDailog(false, "单车使用中", "请您选择其他车辆骑行,谢谢");
                            resultdialog.show();
                        } else {
                            ll_yydc.setVisibility(View.GONE);
                            iv_center.setVisibility(View.VISIBLE);
                            initresultDailog(false, "预约失败", model.getMessage());
                            resultdialog.show();
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    private Dialog resultdialog;

    /**
     * 预约结果dialog
     */
    private void initresultDailog(final boolean issuccess, String title, String msg) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.yuyue_result_dialog, null);
        resultdialog = new Dialog(this, R.style.loading_dialog);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_yuyuedialog_title);
        ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_yuyuedialog_pic);
        TextView tv_msg = (TextView) view.findViewById(R.id.tv_yuyuedialog_msg);
        if (issuccess) {
            tv_title.setText(title);
            tv_title.setTextColor(getResources().getColor(R.color.color_dark));
            iv_pic.setImageResource(R.mipmap.yy_success);
            tv_msg.setText(msg);
        } else {
            tv_title.setText(title);
            tv_title.setTextColor(getResources().getColor(R.color.text_main_3));
            iv_pic.setImageResource(R.mipmap.yy_fail);
            tv_msg.setText(msg);
        }

        ImageView iv_dismis = (ImageView) view.findViewById(R.id.iv_codedialog_dismis);
        iv_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resultdialog.dismiss();
                if (issuccess) {
                    showSuccessPopupWindow();
                } else {
                }
            }
        });
        resultdialog.setContentView(view, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        resultdialog.setCancelable(true);
        resultdialog.setCanceledOnTouchOutside(false);
        resultdialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    class Myhandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    findBictcleByRange(msg.what);
                    break;
                case 2:
                    if (ll_yydc.getVisibility() == View.VISIBLE) {
                        ll_yydc.setVisibility(View.GONE);
                        iv_center.setVisibility(View.VISIBLE);
                    }
                    if (!isyysuccess)
                        findBictcleByRange(msg.what);
                    break;
                case 3:
                    overlay = new MyDrivingRouteOverlay(mBaiduMap);
                    mBaiduMap.setOnMarkerClickListener(overlay);
                    overlay.setData(walkingRouteResult.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();
                    break;
                case 4:
                    myhandler.removeMessages(2);
                    myhandler.removeMessages(3);
                    if (isyysuccess && mylat != 0) {
                        PlanNode stNode = PlanNode.withLocation(new LatLng(mylat, mylng));
                        PlanNode enNode = PlanNode.withLocation(new LatLng(endlat, endlng));

                        mSearch.walkingSearch(new WalkingRoutePlanOption().from(stNode).to(enNode));
                    }
                    break;
            }
        }
    }

    public static Bitmap resizeBitMapImage1(Bitmap MapImage, int targetWidth,
                                            int targetHeight) {
        Bitmap bitMapImage = null;
        // First, get the dimensions of the image
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        bitMapImage = MapImage;
        double sampleSize = 0;
        // Only scale if we need to
        // (16384 buffer for img processing)
        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
                .abs(options.outWidth - targetWidth);
        if (options.outHeight * options.outWidth * 2 >= 1638) {
            // Load, scaling to smallest power of 2 that'll get it <= desired
            // dimensions
            sampleSize = scaleByHeight ? options.outHeight / targetHeight
                    : options.outWidth / targetWidth;
            sampleSize = (int) Math.pow(2d,
                    Math.floor(Math.log(sampleSize) / Math.log(2d)));
        }
        // Do the actual decoding
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[128];
        while (true) {
            try {
                options.inSampleSize = (int) sampleSize;
                bitMapImage = MapImage;
                break;
            } catch (Exception ex) {
                try {
                    sampleSize = sampleSize * 2;
                } catch (Exception ex1) {
                }
            }
        }
        return bitMapImage;
    }

    //lylmarket
    //增加marker标记
    private void initMarket() {
        mBaiduMap.clear();
        MarkerOptions markerOptions;
        for (int i = 0; i < findBictcleByRangeResult.getData().size(); i++) {
            LatLng latLng = new LatLng(findBictcleByRangeResult.getData().get(i).getLastLatitude(), findBictcleByRangeResult.getData().get(i).getLastLongitude());
            //  BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.bicycle);
            BitmapDrawable draw;
            if (findBictcleByRangeResult.getData().get(i).getIsRedBag()) {
                draw = (BitmapDrawable) getResources().getDrawable(R.mipmap.hongbaoche);
            } else {
                draw = (BitmapDrawable) getResources().getDrawable(R.drawable.marker);
//                draw = (BitmapDrawable) getResources().getDrawable(R.drawable.marker);
            }
            Bitmap m = draw.getBitmap();
            Bitmap bm = Bitmap.createScaledBitmap(m, Util.dp2px(this, 40), Util.dp2px(this, 43), true);
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromBitmap(bm);
            markerOptions = new MarkerOptions().icon(bitmap).position(latLng).title(findBictcleByRangeResult.getData().get(i).getPlateNumber());
            markerOptions.animateType(MarkerOptions.MarkerAnimateType.grow);
            //  mBaiduMap.addOverlay(markerOptions);
            mBaiduMap.addOverlay(markerOptions);
        }
        if (isyysuccess) {
            myhandler.sendEmptyMessage(4);
        }
    }

    //lylmarket
    //增加marker标记
    private void initMarket2() {
        mBaiduMap.clear();
//        MarkerOptions markerOptions;
//        for (int i = 0; i < findBictcleByRangeResult.getData().size(); i++) {
//            LatLng latLng = new LatLng(findBictcleByRangeResult.getData().get(i).getLastLatitude(), findBictcleByRangeResult.getData().get(i).getLastLongitude());
//            //  BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.bicycle);
//            BitmapDrawable draw;
//            if (findBictcleByRangeResult.getData().get(i).getIsRedBag()) {
//                draw = (BitmapDrawable) getResources().getDrawable(R.mipmap.hongbaoche);
//            } else {
//                draw = (BitmapDrawable) getResources().getDrawable(R.drawable.marker);
////                draw = (BitmapDrawable) getResources().getDrawable(R.drawable.marker);
//            }
//            Bitmap m = draw.getBitmap();
//            Bitmap bm = Bitmap.createScaledBitmap(m, Util.dp2px(this, 40), Util.dp2px(this, 43), true);
//            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromBitmap(bm);
//            markerOptions = new MarkerOptions().icon(bitmap).position(latLng).title(findBictcleByRangeResult.getData().get(i).getPlateNumber());
//            markerOptions.animateType(MarkerOptions.MarkerAnimateType.grow);
//            //  mBaiduMap.addOverlay(markerOptions);
//            mBaiduMap.addOverlay(markerOptions);
//        }
        LatLng latLng = null;
        OverlayOptions overlayOptions = null;
        Marker marker = null;
        for (FindBictcleByRangeResult.DataBean info : findBictcleByRangeResult.getData()) {
            // 位置
            latLng = new LatLng(info.getLastLatitude(), info.getLastLongitude());
            // 图标
            BitmapDrawable draw;
            if (info.getIsRedBag()) {
                draw = (BitmapDrawable) getResources().getDrawable(R.mipmap.hongbaoche);
            } else {
                draw = (BitmapDrawable) getResources().getDrawable(R.drawable.marker);
//                draw = (BitmapDrawable) getResources().getDrawable(R.drawable.marker);
            }
            Bitmap m = draw.getBitmap();
            Bitmap bm = Bitmap.createScaledBitmap(m, Util.dp2px(this, 40), Util.dp2px(this, 43), true);
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromBitmap(bm);
            overlayOptions = new MarkerOptions().position(latLng)
                    .icon(bitmap).animateType(MarkerOptions.MarkerAnimateType.grow);
//            .zIndex(5)
            marker = (Marker) (mBaiduMap.addOverlay(overlayOptions));
            Bundle bundle = new Bundle();
//            bundle.putSerializable("info", info);
            marker.setExtraInfo(bundle);
        }
        if (isyysuccess) {
            myhandler.sendEmptyMessage(4);
        }
    }

    private FindBictcleByRangeResult findBictcleByRangeResult;

    //刷新单车
    private void findBictcleByRange(final int type) {
        // showProgressDialog();
        LocationInfo locationInfo = new LocationInfo();
        if (type == 1) {
            LocationInfo.DataBean ldb = new LocationInfo.DataBean();
            ldb.setLatitude(mylat + "");
            ldb.setLongitude(mylng + "");
            locationInfo.setModel(ldb);
        } else {
            LocationInfo.DataBean ldb = new LocationInfo.DataBean();
            if (centerlat == 0) {
                ldb.setLatitude(mylat + "");
                ldb.setLongitude(mylng + "");
                Log.e("findBictcleByRange: ", centerlat + "sad" + centerlng);
            } else {
                ldb.setLatitude(centerlat + "");
                ldb.setLongitude(centerlng + "");
                Log.e("findBictcleByRange: ", centerlat + "sad" + centerlng);
            }

            locationInfo.setModel(ldb);
        }
        isshuaxining = true;
        addSubscription(apiStores.FindBictcleByRange(locationInfo),
                new ApiCallback<FindBictcleByRangeResult>() {

                    @Override
                    public void onSuccess(FindBictcleByRangeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            if (model.getData().size() == 0) {
                                ll_fjwdc.setVisibility(View.VISIBLE);
                            }
                            findBictcleByRangeResult = model;
                            try {
                                initMarket2();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        if (type == 1) {
                            LatLng ll = new LatLng(mylat, mylng);
                            MapStatus.Builder builder = new MapStatus.Builder();
                            builder.target(ll).zoom(17.0f);
                            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                        } else
                            toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
//                        iv_refresh.setEnabled(true);
//                        iv_refresh.clearAnimation();
                        if (firstanim) {
                            shuaxinlat = mylat;
                            shuaxinlng = mylng;
                            zoomanim(0, 0);
                            firstanim = false;
                        }
                        h1.sendEmptyMessageDelayed(1, 0);
                        dismissProgressDialog();
                        isshuaxining = false;
                    }
                });
    }

    private Handler h1 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            iv_center.startAnimation(shakeAnim2);
            iv_refresh.setVisibility(View.INVISIBLE);
            //  iv_refresh.clearAnimation();
            iv_refresh.setEnabled(true);
            return false;
        }
    });

    /**
     * 预约成功界面
     */
    private void showSuccessPopupWindow() {
        ll_yydc_succ.setVisibility(View.VISIBLE);

        TextView tv_dis = (TextView) findViewById(R.id.tv_yuyuepop_success_num);
        tv_dis.setText(endnum);
        Countdown tv_time = (Countdown) findViewById(R.id.tv_yuyuepop_success_time);
        tv_time.setTime(0, maxmin, maxsec);
        TextView tv_location = (TextView) findViewById(R.id.tv_yuyuepop_location_succ);
        tv_location.setText(userlocation);
        Button btn_canclebike = (Button) findViewById(R.id.btn_yuyuepop_success_cancle);
        btn_canclebike.setOnClickListener(this);
        ll_fjwdc.setVisibility(View.GONE);
        iv_center.setVisibility(View.GONE);

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void djsmsg(String result) {
        if (result.equals("timeend")) {
            isyysuccess = false;
            iv_center.setVisibility(View.VISIBLE);
            ll_yydc_succ.setVisibility(View.GONE);
            try {
                initMarket2();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 预约界面
     */
    private void showPopupWindow() {
        ll_yydc.setVisibility(View.VISIBLE);

        TextView tv_dis = (TextView) findViewById(R.id.tv_yuyuepop_distence);
        tv_dis.setText(distence);
        TextView tv_time = (TextView) findViewById(R.id.tv_yuyuepop_time);
        tv_time.setText(usetime);
        TextView tv_location = (TextView) findViewById(R.id.tv_yuyuepop_location);
        tv_location.setText(userlocation);
        TextView tv_munit = (TextView) findViewById(R.id.tv_yuyuepop_moneyunit);
        tv_munit.setText(money_unit);
        Button btn_usebike = (Button) findViewById(R.id.btn_yuyuepop_start);
        btn_usebike.setOnClickListener(this);
        ll_fjwdc.setVisibility(View.GONE);
        iv_center.setVisibility(View.GONE);

    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
//        getPersimmions();
//        scanBLE();
        mMapView.onResume();
        myOrientationListener.start();
        //myRiding();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        try {
            if (window.isShowing())
            {
                window.dismiss();
            }
            mLocClient.stop();
            // 关闭定位图层
            myOrientationListener.stop();
            mBaiduMap.setMyLocationEnabled(false);
            mMapView.onDestroy();
            mMapView = null;
            EventBus.getDefault().unregister(this);
            currentDevice = null;
            stopScan();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
//            unbindService(mServiceConnection);
//            mService.stopSelf();
//            mService = null;
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    /*
    @TargetApi(23)
    private void getPersimmions() {
//        PermissionUtils.isCameraPermission(MainActivity.this, 0x007);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();

            // 定位精确位置
            if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if(ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if(ActivityCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.CAMERA);
            }
            if(ActivityCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if(ActivityCompat.checkSelfPermission(this,Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.BLUETOOTH);
            }
            if(ActivityCompat.checkSelfPermission(this,Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.BLUETOOTH_ADMIN);
            }
            if (permissions.size() > 0) {
                ActivityCompat.requestPermissions(this,permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }else{
                if(dialog!=null&&dialog.isShowing()){
                    dialog.dismiss();
                }
            }
        }
    }


    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case SDK_PERMISSION_REQUEST:
            for(int i=0;i<grantResults.length;i++){
                if (grantResults[i]== PackageManager.PERMISSION_GRANTED){
                    if(dialog!=null&&dialog.isShowing()){
                        dialog.dismiss();
                    }
                }else{
                    if(dialog==null||!dialog.isShowing())
                        showMissingPermissionDialog();
                }
            }
            break;
        }
    }
    private  Dialog dialog;
    // 显示缺失权限提示
    private void showMissingPermissionDialog() {
        dialog= CustomerDialog.createDeletaDialog(this, "是否添加权限？", new MyOnclicklistener());
        dialog.show();
    }
    class MyOnclicklistener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.tv_deletedialog_cancle:
                    finish();
                    break;
                case R.id.tv_deletedialog_delete:
                    dialog.dismiss();
                    startAppSettings();
                    break;
            }
        }
    }


*/
    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    private void setDrivingpop() {//骑行对话框
        View popupView = this.getLayoutInflater().inflate(R.layout.pop_enddriving, null);
        window = new PopupWindow(popupView, 400, 600);
        window.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        window.setHeight((int) (getScreenh(this) * 0.35));
        window.setAnimationStyle(R.style.mypopwindow_anim_style2);
        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));
        window.setFocusable(false);
        window.setOutsideTouchable(false);
        window.update();
        popbutton = (Button) popupView.findViewById(R.id.driving_bt);
        drivetime = (TextView) popupView.findViewById(R.id.driving_timetv);
        drivefar = (TextView) popupView.findViewById(R.id.driving_fartv);
        drivehot = (TextView) popupView.findViewById(R.id.driving_hottv);
        bikenum = (TextView) popupView.findViewById(R.id.driving_numtv);
        pricepop = (TextView) popupView.findViewById(R.id.driving_pricetv);
    }

    private void showdrivingpop() {//显示对话框
        iv_scan.setVisibility(View.INVISIBLE);
        iv_scan.setEnabled(false);
        //举报一直显示
//        iv_tel.setVisibility(View.INVISIBLE);
//        iv_tel.setEnabled(false);
        shouldshowending = true;
        if (window.isShowing()) {
        } else {
            try {
                window.showAsDropDown(bar_btn_rly, 0, 2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        popbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intentweijiesuanjubao = new Intent(MainActivity.this, JvBaonotitleActivity.class);
//                intentweijiesuanjubao.putExtra("bikenum", plantnum);
//                startActivityForResult(intentweijiesuanjubao, 123);//用户冻结
                getMacguansuo(plantnum);
            }
        });
    }

    private int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static int getScreenw(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);

        return outMetrics.widthPixels;
    }

    public static int getScreenh(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);

        return outMetrics.heightPixels;
    }

    @Subscribe(threadMode = ThreadMode.MainThread, sticky = true)
    public void endride(MyReceiverResult progress) {
        EventBus.getDefault().removeStickyEvent(progress);
//        progress.getPlateNumber().equals(bikenum.getText().toString())
        if (true) {
            if (hasshowendinfo) {
                //Toast.makeText(this, "行程结束", Toast.LENGTH_SHORT).show();
            } else {
                shouldshowending = false;
//                if (window!=null)
//                {
//                    window.dismiss();
//                }
//                if (iv_scan!=null)
//                {
//                    iv_scan.setVisibility(View.VISIBLE);
//                    iv_scan.setEnabled(true);
//                }
                Intent intent = new Intent(this, RaidingEndActivity.class);
                intent.putExtra("ists", true);
                intent.putExtra("msg", progress);
                intent.putExtra("needpay", progress.isNeedPay());
                startActivityForResult(intent, 10001);
                reloadAccountInfo();
                hasshowendinfo = true;
                hastongzhi = true;
            }
        } else {
            return;
        }
    }

    //
//        @Subscribe(threadMode = ThreadMode.MainThread)
//    public void startride(String str) {
//        if (str.endsWith(",1111")) {
//            Log.e("startride: ", str);
//            startplantnum = str.split(",")[1];
//            deviceId = startplantnum;
//            mac = str.split(",")[3];
//            SharedPreferences.Editor edit = preferences.edit();
//            edit.putString("macc", mac);
//            edit.commit();
//            if (hastongzhi) {
//                Log.e("kaisuo ", "去通知");
//                tzfuq();
//
//            }
//            EventBus.getDefault().cancelEventDelivery(str);
//        }
//    }
            @Subscribe(threadMode = ThreadMode.MainThread)
    public void jiantingdaohehuorenbuy(String str) {
        if (str.equals("hehuorenbuyok")) {
            ischenghsihehuoren=true;
            reloadAccountInfo();
        }
    }
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void startride(KaiSuoResult model) {
        {
            hasshowendinfo = false;
            qixingjuli = 0;
            qixingreliang = 0;
            hf = 0;
            hb = 0;
            mf = 0;
            mb = 0;
            sf = 0;
            sb = 0;
            isriding = true;
            showdrivingpop();
            setdrivinginfo(model);
            drivefar.setText(qixingjuli + "米");
            drivehot.setText(qixingreliang + "大卡");
            try {
                if (myhandlertime != null) {
                    myhandlertime.removeMessages(1);
                }
                if (myhandlertime==null)
                {
                    myhandlertime = new Myhandlertime();
                }
                myhandlertime.sendEmptyMessageDelayed(1, 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (window != null) {
                window.setHeight((int) (getScreenh(this) * 0.35));
            }
        }
    }

    //计算骑行过程
    private double qixingjuli = 0;
    private double qixingreliang = 0;
    private int hf, hb, mf, mb, sf, sb;
    private boolean ismax = false;
    private String plantnum, moneyunit;
    private Long timepast;
    private Myhandlertime myhandlertime;
    private boolean hasshowendinfo = false;

    private void setdrivinginfo(KaiSuoResult model) {
        timepast = 0L;
        moneyunit = money_unit;
        plantnum = model.getData().getPlateNumber();
        bikenum.setText(plantnum);
    }

    private void setdrivinginfo(MyRidingResult model) {
        timepast = timehapast;
        moneyunit = money_unit;
        plantnum = model.getData().getPlateNumber();
        if (timepast != 0) {
            hf = (int) (timepast / 3600) / 10;
            hb = (int) (timepast / 3600) % 10;

            mf = (int) (timepast % 3600) / 60 / 10;
            mb = (int) (timepast % 3600) / 60 % 10;

            sf = (int) (timepast % 60) / 10;
            sb = (int) (timepast % 60) % 10;
            // mb = (int) (timepast / 60);
        }
        bikenum.setText(plantnum);
//        km×体重(kg)×1.05
    }

    DecimalFormat df = new DecimalFormat("######0.00");
    DecimalFormat df2 = new DecimalFormat("######0");

   private  class Myhandlertime extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                sb++;
                if (sb == 10) {
                    sb = 0;
                    sf++;
                }
                if (sf == 6) {
                    sf = 0;
                    mb++;
                }
                if (mb == 10) {
                    mb = 0;
                    mf++;
                }
                if (mf == 6) {
                    mf = 0;
                    hb++;
                }
                if (hb == 10) {
                    hb = 0;
                    hf++;
                }
                if (hf == 10) {
                    hf = 9;
                    ismax = true;
                }
//            if (hf+hb == 0) {
//                drivetime.setText(mf + "" + mb + "分" + sf + "" + sb + "秒");
//            } else if (mf + mb == 0) {
//                drivetime.setText(sf + "" + sb + "秒");
//            } else {
//                drivetime.setText(hf + "" + hb + "时" + mf + "" + mb + "分" + sf + "" + sb + "秒");
//            }
                try {
                    drivetime.setText(hf + "" + hb + " : " + mf + "" + mb + " : " + sf + "" + sb + "");
                    // drivetime.setText((mb + 1) + "分");：：::::::::：：：：
                    drivefar.setText(df2.format(qixingjuli) + "米");
                    settextcolorwithstr(drivefar, "米", getResources().getColor(R.color.text_main_6));
                    if (qixingjuli > 1000) {
                        drivefar.setText(df.format(qixingjuli * 0.001) + "千米");
                        settextcolorwithstr(drivefar, "千米", getResources().getColor(R.color.text_main_6));
                    }
                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                }
                try {
                    drivehot.setText(df2.format(qixingreliang) + "大卡");
                    settextcolorwithstr(drivehot, "大卡", getResources().getColor(R.color.text_main_6));
                    pricepop.setText(df.format((hf * 10 + hb + 1) * Double.parseDouble(moneyunit)) + "元");
                    settextcolorwithstr(pricepop, "元", getResources().getColor(R.color.text_main_6));
                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                try {
                    if (!ismax)
                        if (myhandlertime != null) {
                            myhandlertime.removeMessages(1);
                        }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    if (myhandlertime != null) {
                        myhandlertime.sendEmptyMessageDelayed(1, 1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void setteldialog() {
        teldialog = new AlertDialog.Builder(this).setTitle("是否拨打客服电话").setMessage(Config.TEL).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Uri uri = Uri.parse("tel:" + Config.TEL);
                Intent intenttel = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(intenttel);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).create();
        //teldialog.setCanceledOnTouchOutside(false);
    }

    private Handler handler100;

    private void zoomanim(final double m1, final double m2) {
        if (m1 == 0) {
            final MapStatus.Builder builder = new MapStatus.Builder();
            builder.zoom(15.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()), 600);
        } else {
            final LatLng ll = new LatLng(m1, m2);
            final MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(15.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()), 600);
        }
        if (handler100 == null) {
            handler100 = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message message) {
                    if (m1 == 0) {
                        MapStatus.Builder builder2 = new MapStatus.Builder();
                        builder2.zoom(17f);
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder2.build()), 600);
                    } else {
                        LatLng ll = new LatLng(m1, m2);
                        MapStatus.Builder builder2 = new MapStatus.Builder();
                        builder2.target(ll).zoom(17f);
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder2.build()), 600);
                    }
                    myhandler.sendEmptyMessageDelayed(2, 600);
                    return false;
                }
            });
        }
        handler100.sendEmptyMessageDelayed(1, 600);
//        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
//            @Override
//            public void onMapStatusChangeStart(MapStatus mapStatus) {
//
//            }
//
//            @Override
//            public void onMapStatusChange(MapStatus mapStatus) {
//
//            }
//
//            @Override
//            public void onMapStatusChangeFinish(MapStatus mapStatus) {
//                {
//                    LatLng ll = new LatLng(m1, m2);
//                    MapStatus.Builder builder2 = new MapStatus.Builder();
//                    builder2.target(ll).zoom(19.0f);
//                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder2.build()),800);
//                    mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
//                        @Override
//                        public void onMapStatusChangeStart(MapStatus mapStatus) {
//
//                        }
//
//                        @Override
//                        public void onMapStatusChange(MapStatus mapStatus) {
//
//                        }
//
//                        @Override
//                        public void onMapStatusChangeFinish(MapStatus mapStatus) {
//
//                        }
//                    });
//                }
//            }
//        });

    }

    /**
     * 27. 是否有充20送单车活动
     */
    private void has20danche() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.TwentyActivity(params),
                new ApiCallback<TwentyActivityResult>() {
                    @Override
                    public void onSuccess(TwentyActivityResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            huodongdanche20 = model.getData().getAmount();
                            hasbuy20danche = model.getData().isSuccess();
                            imagesBeen.clear();
                            imagesBeen = model.getData().getImages();
                            DataSingle.getInstance().imagesBeen = imagesBeen;
                            if (model.getData().isIsShow()) {
                                has20 = true;
                                ll_chong20.setVisibility(View.GONE);
                            } else {
                                ll_chong20.setVisibility(View.GONE);
                                has20 = false;
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                        ll_chong20.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFinish() {
                        if (imagesBeen != null && imagesBeen.size() > 0)
                            setimage(imagesBeen);
                    }
                });
    }

    private void setimage(List<TwentyActivityResult.DataBean.ImagesBean> images) {
        //   iv20huodongtitile.setVisibility();
        try {
            Util.setRviewwh(tvdongjie, Integer.parseInt(images.get(0).getWidth()), Integer.parseInt(images.get(0).getHeight()), 1);
            Util.setLviewwh(iv20huodongtitile, Integer.parseInt(images.get(0).getWidth()), Integer.parseInt(images.get(0).getHeight()), 0.9);
            Picasso.with(mActivity).load(images.get(0).getImagePath()).networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE).into(iv20huodongtitile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //举报对话框
    private void setjubaoDialog() {
        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.bgwhite);
        Bitmap bitmap = ImgUtils.convertToBlur(bm);
        bitmap.setHasAlpha(true);
        RelativeLayout ivv;
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        final View headview = inflater.inflate(R.layout.jubao_dialog, null, false);
        ivv = headview.findViewById(R.id.ivv);
        BitmapDrawable bd = new BitmapDrawable(bitmap);
        ivv.setBackground(bd);
        ivv.setAlpha(0.9f);
        jubaodialog = new Dialog(this, R.style.Dialog_Fullscreen);
        jubaodialog.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        Window dialogWindow = jubaodialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        lp.width = DataSingle.getInstance().PhoneW; // 宽度
//        lp.height = (int) (DataSingle.getInstance().PhoneH*0.3); // 宽度
//         lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setWindowAnimations(R.style.mypopwindow_anim_style3);  //添加动画
        dialogWindow.setAttributes(lp);
        ImageView guansuohouweijiesuan = headview.findViewById(R.id.guansuohouweijiesuan);
        ImageView cheliangguzhang = headview.findViewById(R.id.cheliangguzhang);
        cheliangguzhang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
                Intent intentjubao = new Intent(MainActivity.this, JvBaoActivity.class);
                startActivityForResult(intentjubao, 10000);

            }
        });
        guansuohouweijiesuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
                Intent intentzhinan = new Intent(MainActivity.this, ZhiNanActivity.class);
                startActivityForResult(intentzhinan, 123);
            }
        });
    }

    private void settextcolorwithstr(TextView view, String str, int color) {
        int fstart = view.getText().toString().indexOf(str);
        int fend = fstart + str.length();
        SpannableStringBuilder style = new SpannableStringBuilder(view.getText().toString());
        style.setSpan(new ForegroundColorSpan(color), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        view.setText(style);
    }

    //    private void jiantinglanya(){
//        String action=BluetoothAdapter.ACTION_STATE_CHANGED;
//        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
//            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
//                    BluetoothAdapter.ERROR);
//            switch (state) {
//                case BluetoothAdapter.STATE_OFF:
//                    Log.d("aaa", "STATE_OFF 手机蓝牙关闭");
//                    break;
//                case BluetoothAdapter.STATE_TURNING_OFF:
//                    Log.d("aaa", "STATE_TURNING_OFF 手机蓝牙正在关闭");
//                    break;
//                case BluetoothAdapter.STATE_ON:
//                    Log.d("aaa", "STATE_ON 手机蓝牙开启");
//                    break;
//                case BluetoothAdapter.STATE_TURNING_ON:
//                    Log.d("aaa", "STATE_TURNING_ON 手机蓝牙正在开启");
//                    break;
//            }
//        }
//    }
    private void getMacguansuo(String deviceId) {
        Intent intentweijiesuanjubao = new Intent(MainActivity.this, OpenResultActivity.class);
        intentweijiesuanjubao.putExtra("bikenum", plantnum);
        intentweijiesuanjubao.putExtra("DEVICEID", deviceId);
        intentweijiesuanjubao.putExtra("TYPE", 1);
        intentweijiesuanjubao.putExtra("latu", mylat);
        intentweijiesuanjubao.putExtra("long", mylng);
        intentweijiesuanjubao.putExtra("BLEADDRESS", preferences.getString("macc", ""));
        startActivityForResult(intentweijiesuanjubao, 208);//去关锁界面
    }

    private boolean isfirstkaisuo = true;

    private void isfirstkaisuo() {
        isfirstkaisuo = preferences.getBoolean("isfirstkaisuo", true);
        if (isfirstkaisuo) {
            settixiannewDialog();
        } else {
            if (!ishaveenoughmoney(true)) {
                if (checkly()) {
                    if (PermissionTool.isCameraCanUse()) {
                        Intent intent = new Intent(MainActivity.this, DeviceScanActivity.class);
//                        Intent intent = new Intent(MainActivity.this, TongyongSaomaActivity.class);
                        intent.putExtra("latu", mylat);
                        intent.putExtra("long", mylng);
//                            Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                        // Intent intent = new Intent(MainActivity.this, NewScanActivity.class);
                        startActivityForResult(intent, 5000);
                    } else {
                        toastShow("没有获取相机权限,请手动设置应用权限");
                    }
                } else {
                    toastShow("打开蓝牙失败,请手动打开蓝牙");
                    startAppSettings();
                }
                //扫码界面
            }
        }
    }

    //第一次开锁对话框1
    private void settixiannewDialog() {
        final RelativeLayout rly1, rly2;
        TextView note1, note2;
        LayoutInflater inflater = LayoutInflater.from(this);
        final View headview = inflater.inflate(R.layout.firstkaisuo_dialog, null, false);
        firstkaisuodialog = new Dialog(this, R.style.Dialog_Fullscreen);
        firstkaisuodialog.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        firstkaisuodialog.setCanceledOnTouchOutside(true);
        rly1 = headview.findViewById(R.id.firstkaisuoly1);
        rly2 = headview.findViewById(R.id.firstkaisuoly2);
        rly2.setVisibility(View.INVISIBLE);
        note1 = headview.findViewById(R.id.firstkaisuotv1);
        note2 = headview.findViewById(R.id.firstkaisuotv2);
        note1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rly2.setVisibility(View.VISIBLE);
            }
        });
        note2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor edit = preferences.edit();
                edit.putBoolean("isfirstkaisuo", false);
                edit.commit();
                if (!ishaveenoughmoney(true)) {
                    if (checkly()) {
                        if (PermissionTool.isCameraCanUse()) {
                            Intent intent = new Intent(MainActivity.this, DeviceScanActivity.class);
                            intent.putExtra("latu", mylat);
                            intent.putExtra("long", mylng);
//                            Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                            // Intent intent = new Intent(MainActivity.this, NewScanActivity.class);
                            startActivityForResult(intent, 5000);
                        } else {
                            toastShow("没有获取相机权限,请手动设置应用权限");
                        }
                    } else {
                        toastShow("打开蓝牙失败,请手动打开蓝牙");
                        startAppSettings();
                    }
                    //扫码界面
                }
                firstkaisuodialog.dismiss();
            }
        });
        Window dialogWindow = firstkaisuodialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
//        lp.width = (int) (DataSingle.getInstance().PhoneW * 0.75); // 宽度
//        lp.height = (int) (DataSingle.getInstance().PhoneW * 0.75);
//         lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setWindowAnimations(R.style.mypopwindow_anim_style3);  //添加动画
        dialogWindow.setAttributes(lp);
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        };
//        firstkaisuodialog.setOnKeyListener(keylistener);
        firstkaisuodialog.show();
    }
}
